package com.xiehua.task.actor;

import akka.actor.AbstractActor;
import akka.actor.ActorRef;
import akka.actor.ActorSelection;
import com.xiehua.task.actor.cmd.Cmd;
import com.xiehua.task.job.PostOffice;
import com.xiehua.task.monitor.Statistics;
import com.xiehua.task.monitor.dingding.Robot;
import com.xiehua.task.redis.RedisTemplate;
import com.xiehua.task.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.exceptions.JedisConnectionException;

import static com.xiehua.task.actor.cmd.Cmd.CMD_SEND_EMAIL;
import static com.xiehua.task.monitor.Statistics.EMAIL_TYPE_EXCETPION;

public class EmailActor extends AbstractActor {

    private static final Logger LOGGER = LoggerFactory.getLogger(EmailActor.class);

    @Override
    public AbstractActor.Receive createReceive() {
        return receiveBuilder().match(Cmd.class, t -> t.getCmd().equals(Cmd.CMD_SEND_EMAIL), s -> {
            if (LOGGER.isDebugEnabled()) LOGGER.debug("收到消息type：{}", s.getCmd());
            Object o = s.getT();
            if (o != null) {
                Statistics statistics = (Statistics) o;
                //发送钉钉
                if (EMAIL_TYPE_EXCETPION.equals(statistics.getType()) && statistics.getException() instanceof JedisConnectionException){
                    new Robot().talk(statistics);
                }
                //投递邮件
                PostOffice postOffice = new PostOffice(RedisTemplate.getJedis());
                postOffice.delivery(statistics);
                postOffice.clear();
            }
        }).matchAny(t -> {
            LOGGER.error("没有对应Actor处理本次消息~");
            unhandled(t);
        }).build();
    }

    public static void sendExceptionEmail(Exception e, ActorRef target, ActorRef sender, String topic) {
        Cmd<Statistics> cmd = genStatisticsCmd(e, topic);
        target.tell(cmd, sender);
    }

    public static void sendExceptionEmail(Exception e, ActorSelection target, ActorRef sender, String topic) {
        Cmd<Statistics> cmd = genStatisticsCmd(e, topic);
        target.tell(cmd, sender);
    }

    private static Cmd<Statistics> genStatisticsCmd(Exception e, String topic) {
        Statistics statistics = new Statistics();
        statistics.setType(EMAIL_TYPE_EXCETPION);
        statistics.setException(e);
        if (!StringUtils.isEmpty(topic)) statistics.setTopic(topic);
        return new Cmd<>(CMD_SEND_EMAIL, statistics);
    }

}
